﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace Soft.Net
{


    public class ClientIPServerSink : BaseChannelObjectWithProperties, IServerChannelSink, IChannelSinkBase
    {
        public ClientIPServerSink(IServerChannelSink nextChannelSink)
        {
            this.NextChannelSink = nextChannelSink;
        }

  
        public IServerChannelSink NextChannelSink { get; set; }


        public void AsyncProcessResponse(IServerResponseChannelSinkStack sinkStack, object state, IMessage msg, ITransportHeaders headers, Stream stream)
        {
        }


        public Stream GetResponseStream(IServerResponseChannelSinkStack sinkStack, object state, IMessage msg, ITransportHeaders headers)
        {
            return null;
        }


        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            if (this.NextChannelSink != null)
            {
                IPAddress data = requestHeaders["__IPAddress"] as IPAddress;
                CallContext.SetData("ClientIPAddress", data);
                return this.NextChannelSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream);
            }
            responseMsg = null;
            responseHeaders = null;
            responseStream = null;
            return ServerProcessing.Complete;
        }
    }
}
